import { useRef, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { ProDescriptions, ProList } from '@ant-design/pro-components';
import { Button, message, Popconfirm } from 'antd';
import { history, useModel } from 'umi';

import PageContainer from '@/components/PageContainer';
import request, { requestWithoutCache } from '@/utils/request';
import { tsFmtLongDate } from '@/utils/time';

import GroupForm from './components/GroupForm';

import styles from './components/index.less';

const StoreGroup = () => {
  const listRef = useRef();
  const [operation, setOperation] = useState({});
  const [isOpenDrawer, setIsOpenDrawer] = useState(false);
  const [activeKey, setActiveKey] = useState('my');
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState.currentUser.username;

  const onReloadData = () => {
    listRef.current.reload();
    setOperation();
    setIsOpenDrawer(false);
  };

  const deleteStore = async (id) => {
    await request(`/api/url/${id}`, { method: 'DELETE' }).then(() => {
      message.success('删除仓库成功!!!');
      listRef.current.reload();
    });
  };

  return (
    <PageContainer>
      <GroupForm
        open={!!isOpenDrawer}
        onOpenChange={setIsOpenDrawer}
        onReloadData={onReloadData}
        {...operation}
      />
      <ProList
        pagination={{
          pageSize: 12,
          showSizeChanger: false,
        }}
        headerTitle="仓库列表"
        actionRef={listRef}
        rowKey="id"
        rowClassName={styles.list}
        itemCardProps={{
          bodyStyle: {
            padding: '15px',
          },
          style: {
            height: '100%',
          },
        }}
        onItem={(record) => {
          return {
            onClick: () => {
              history.push(`/code/detail?id=${record.id}`);
            },
          };
        }}
        grid={{ gutter: 16, column: 3 }}
        metas={{
          title: {
            render: (_, { name }) => name,
          },
          content: {
            render: (_, { desc, created_at }) => (
              <ProDescriptions column={1}>
                <ProDescriptions.Item label="描述">
                  {desc || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="创建时间">
                  {tsFmtLongDate(created_at)}
                </ProDescriptions.Item>
              </ProDescriptions>
            ),
          },
          actions: {
            render: (_, { id, username }) => {
              const isCreator = currentUser === username;
              return [
                <Button
                  key="edit"
                  type="link"
                  size="small"
                  disabled={!isCreator}
                  onClick={() => {
                    setOperation({
                      id,
                      type: 'edit',
                    });
                    setIsOpenDrawer(true);
                  }}
                >
                  修改
                </Button>,
                <Popconfirm
                  title="确认删除该仓库嘛?"
                  onConfirm={() => deleteStore(id)}
                  key="delete"
                  disabled={!isCreator}
                >
                  <Button disabled={!isCreator} type="link" size="small">
                    删除
                  </Button>
                </Popconfirm>,
              ];
            },
          },
        }}
        params={{ activeKey }}
        request={async (params) => {
          const resp = await requestWithoutCache('/api/url', {
            method: 'GET',
            params: {
              name: params.keyword,
              ...(activeKey === 'my' ? { username: currentUser } : {}),
            },
          });
          return {
            data: resp.data,
            success: resp.success,
            total: resp.total,
          };
        }}
        search={false}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey,
            items: [
              {
                key: 'my',
                label: <span>我的</span>,
              },
              {
                key: 'all',
                label: <span>全部</span>,
              },
            ],
            onChange: setActiveKey,
          },
          actions: [
            <Button
              key="createStore"
              type="primary"
              onClick={() => {
                setOperation({
                  type: 'create',
                });
                setIsOpenDrawer(true);
              }}
            >
              <PlusOutlined />
              新增仓库
            </Button>,
          ],
        }}
        options={{
          search: true,
          reload: false,
          setting: false,
          density: false,
        }}
      />
    </PageContainer>
  );
};

export default StoreGroup;
